package com.msb.mallcart.Interceptor;

import com.msb.common.constant.AuthConstant;
import com.msb.common.vo.MemberVO;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Auther: xixifeng
 * @Date: 2022/11/10 - 11 - 10 - 18:19
 * @Description: com.msb.mallcart.Interceptor
 * @version: 1.0
 */
//自定义拦截器
public class AuthInterceptor implements HandlerInterceptor {

    // 本地线程对象  Map<thread,Object>
    public static ThreadLocal<MemberVO> threadLocal=new ThreadLocal();

    /**
     * 我们自定义的拦截器：帮助我们获取当前登录的用户信息
     *     通过Session共享获取的
     */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            // 通过HttpSession获取当前登录的用户信息
            HttpSession session = request.getSession();
            Object attribute = session.getAttribute(AuthConstant.AUTH_SESSION_REDIS);
            if (attribute != null) {
                MemberVO memberVO=(MemberVO)attribute;
                threadLocal.set(memberVO);
                return true;
            }
            // 如果 attribute == null 说明没有登录，那么我们就需要重定向到登录页面
            session.setAttribute(AuthConstant.AUTH_SESSION_MSG,"请先登入");
            response.sendRedirect("http://mall.msb.com:8040/home");
            return false;
    }
}
